package com.itheima.task;

import com.itheima.mapper.EmpMapper;
import com.itheima.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Slf4j
@Component
public class CleanImageTask {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    @Autowired
    private EmpMapper empMapper;

    @Scheduled(cron = "0/3 * * * * ?")
    public void removeOSSImage(){
        log.info("开始清理图片");
        //查询阿里上的所有的图片
        try {
            List<String> imagesInOss = aliyunOSSOperator.listFiles();
            int ossSize = imagesInOss==null?0:imagesInOss.size();
            log.info("阿里oss上共有{}张图片", ossSize);
            if(ossSize > 0){
                //查询数据库员工表中的所有图片
                List<String> imagesInDB =empMapper.selectAllImages();
                log.info("数据库中有{}张图片", imagesInDB.size());
                if(!CollectionUtils.isEmpty(imagesInDB)){
                    //去除前缀 https://sz154-web.oss-cn-shenzhen.aliyuncs.com/
                    imagesInDB.replaceAll(image -> image.replace("https://sz154-web.oss-cn-shenzhen.aliyuncs.com/", ""));
                }
                //oss - db = 垃圾图片
                imagesInOss.removeAll(imagesInDB);
                log.info("需要删除的图片共{}张", imagesInOss.size());
                if(imagesInOss.size() > 0){
                    aliyunOSSOperator.deleteFiles(imagesInOss);
                    log.info("成功删除了oss上{}张图片", imagesInOss.size());
                }
            }
        } catch (Exception e) {
            log.error("访问阿里oss失败.", e);
            return;
        }
        log.info("删除图片任务完成.");
    }
}
